<!-- 最简单的年月日选择器 -->

<template>
    <view class="date-picker-container">
        <!-- 日期范围选择区域 -->
        <view class="date-range-picker">
            <!-- 开始日期选择器 -->
            <picker style=" display:flex; justify-content: center;align-items: center; height: 37px;width: 200px;" mode="date" :value="formatPickerValue(startDate)" :start="startYear" :end="endYear" fields="day"
                @change="(e: any) => handlePickerChange(e, 'start')" @cancel="() => handlePickerCancel('start')">
                <!-- <uni-easyinput :value="startDate" placeholder="请选择开始日期" readonly :disabled="true"></uni-easyinput> -->
            <!-- <view style="height: 37px;width: 200px;background-color: aliceblue;">{{ startDate }}</view> -->
            <text>{{ startDate }}</text>
            </picker>

            <text class="range-separator">至</text>

            <!-- 结束日期选择器 -->
            <picker style=" display:flex; justify-content: center;align-items: center; height: 37px;width: 200px;"  mode="date" :value="formatPickerValue(endDate)" :start="startYear" :end="endYear" fields="day"
                @change="(e: any) => handlePickerChange(e, 'end')" @cancel="() => handlePickerCancel('end')">
                <!-- <uni-easyinput :clearable="false" :value="endDate" placeholder="请选择结束日期" readonly></uni-easyinput> -->
            <text>{{ endDate }}</text>
            
            </picker>
        </view>

        <!-- 进度条显示 -->
        <!-- <view v-show="showProgress" class="progress-container">
      <view class="progress-bar" :style="{ width: progress + '%' }"></view>
    </view> -->
    </view>
</template>

<script setup lang="ts">
// 导入Vue3核心API
import { ref, onMounted, watch } from 'vue';

const emit = defineEmits(['update:startDate', 'update:endDate']);






const props = defineProps({
    startDate: {
        type: String,
        default: ''
    },
    endDate: {
        type: String,
        default: ''
    }
})


// 响应式变量定义
const startDate = ref(props.startDate); // 开始日期值
const endDate = ref(props.endDate);   // 结束日期值
const startYear = ref(''); // 日期选择器的起始年份
const endYear = ref('');   // 日期选择器的结束年份
// 监听开始日期和结束日期变化
watch(startDate, (newVal) => {
    emit('update:startDate', newVal);
})

watch(endDate, (newVal) => {
    emit('update:endDate', newVal);
})
// 进度显示相关数据
// const progress = ref(0);
// const showProgress = ref(false);

// 组件挂载时执行
onMounted(() => {
    // 获取当前年份，设置选择器的年份范围（前后10年）
    const currentYear = new Date().getFullYear();
    startYear.value = (currentYear - 10).toString();
    endYear.value = (currentYear + 10).toString();

    // 获取当前日期并格式化为YYYY-MM-DD
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');

    // 设置结束日期和开始日期
    const formattedDate = `${year}-${month}-${day}`;
    endDate.value = formattedDate;
    startDate.value = formattedDate;
});

// 处理选择器变化事件
const handlePickerChange = (e: any, type: 'start' | 'end') => {
    let value = e.detail.value;

    // 直接设置日期值
    if (type === 'start') {
        startDate.value = formatDate(value);
    } else {
        endDate.value = formatDate(value);
    }
};
// 格式化日期显示（只保留年月日格式）
const formatDate = (value: string | string[]): string => {
    // 如果是数组，先合并成字符串
    if (Array.isArray(value)) {
        value = value.join(' ');
    }

    const strValue = value.toString();
    // 只取日期部分（YYYY-MM-DD）
    return strValue.split(' ')[0];
};
// 格式化日期为选择器期望的格式
const formatPickerValue = (value: string): string => {
    // 处理空值情况
    if (!value) {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 确保返回YYYY-MM-DD格式
    const dateParts = value.split('-');
    if (dateParts.length === 3) {
        return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`;
    }

    // 处理其他可能的格式
    const date = new Date(value);
    if (!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    return value;
};
// 处理选择器取消事件
const handlePickerCancel = (type: 'start' | 'end') => {
    // 取消选择时，确保选择器下次打开时使用的是输入框的当前值
    // 通过先设置为空再恢复原值的方式，强制触发响应式更新
    if (type === 'start') {
        const temp = startDate.value;
        startDate.value = '';  // 先设置为空值
        setTimeout(() => {
            startDate.value = temp;  // 延迟恢复原值，强制触发更新
        }, 0);
    } else {
        const temp = endDate.value;
        endDate.value = '';  // 先设置为空值
        setTimeout(() => {
            endDate.value = temp;  // 延迟恢复原值，强制触发更新
        }, 0);
    }

    console.log(`取消${type === 'start' ? '开始' : '结束'}日期选择`);
};
</script>

<style scoped>
/* 容器样式 */
.date-picker-container {
    padding: 20rpx;
}

/* 日期范围选择区域样式 */
.date-range-picker {
    display: flex;
    align-items: center;
    gap: 20rpx;
    border: 1px solid #9f9e9e;
    background-color: rgb(237, 237, 237);
    border-radius: 20rpx;
}

/* 输入框样式 */
.date-range-picker uni-easyinput {
    flex: 1;
}

/* 分隔符样式 */
.range-separator {
    font-size: 32rpx;
    color: #666;
}

/* 进度条样式 */
/* .progress-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background-color: #f0f0f0;
  z-index: 9999;
} */

/* .progress-bar {
  height: 100%;
  background-color: #007aff;
  transition: width 0.3s ease;
} */
</style>